//
// Created by 张兮兮 on 2025/3/13.
//

#include "Worker.h"
#include <QBuffer>
#include <QDebug>
#include <QDir>
Worker::Worker(QObject *parent)
{

}



void Worker::handleProcessOutput() {
    QByteArray outputError = process->readAllStandardError();
    QByteArray output = process->readAllStandardOutput();
    if (!outputError.isEmpty()) {
        qDebug() << "222222output:" << outputError;
    }
    if (!output.isEmpty()) {
        qDebug() << "1111111output:" << output;
    }
    if (outputError.contains("Server started successfully") || output.contains("Server started successfully")) {
        // 服务器已经启动，尝试连接
        socket->connectToServer(socketPath);
        if (socket->waitForConnected(3000)) {
        } else {
            qDebug() << "Unable to connect to server:" << socket->errorString();
        }
    }
//    qDebug() << "来爱仕达奋斗啥方式了";
}
Worker::~Worker() {
    qDebug()<<"我被销毁了";
    emit workerStopped();
    disconnect();
}

void Worker::processImage(const QImage &image) {
    qDebug() << "Worker 线程收到图片：" << QThread::currentThread();
    if (!running || socket->state() != QLocalSocket::ConnectedState) return;
    QByteArray imageData;
    QBuffer buffer(&imageData);
    if (!buffer.open(QIODevice::WriteOnly)) {
        qWarning() << "Failed to open buffer for writing";
        return;
    }
    if (!image.save(&buffer, "JPG")) {
        qWarning() << "Failed to save image to buffer";
        return;
    }
    buffer.close();
    qint64 imageSize = imageData.size();


    bool flag = true;


    qint64 bytesWritten = socket->write(reinterpret_cast<const char *>(&flag), sizeof(flag));
    qDebug() << "Writing flag:" << flag << "bytesWritten:" << bytesWritten;
    if (bytesWritten != sizeof(flag)) {
        qWarning() << "Failed to write flag to socket";
        return;
    }


    bytesWritten = socket->write(reinterpret_cast<const char *>(&imageSize), sizeof(imageSize));
    qDebug() << "Writing image size:" << imageSize << "bytesWritten:" << bytesWritten;
    if (bytesWritten != sizeof(imageSize)) {
        qWarning() << "Failed to write image size to socket";
        return;
    }
    if (!socket->waitForBytesWritten()) {
        qWarning() << "Error while waiting for image size data to be written";
        return;
    }
    bytesWritten = socket->write(imageData);
    if (bytesWritten != imageSize) {
        qWarning() << "Failed to write full image data to socket";
        return;
    }
    if (!socket->waitForBytesWritten()) {
        qWarning() << "Error while waiting for image data to be written";
    } else {
        imageData.clear();
    }
}


void Worker::init() {
    qDebug() << "Worker init线程创建：" << QThread::currentThread();
    qDebug() << "Worker 线程创建：" << QThread::currentThread();
    socket = new QLocalSocket(this);
    connect(socket, &QLocalSocket::readyRead, this, [this]() {
        QByteArray data = socket->readAll();
        emit resultReady(QString::fromUtf8(data));
    });

    process = new QProcess(this);
    pid_t pid = 23043;
    QString processId = "socketHandPro" + QString::number(pid);
    qDebug() << "当前进程id" << processId;
    // 启动 socket 进程
    QString program = "/Users/zhanghongwei/Desktop/socket-temp/socket-project/build/Debug/socketPro";
    QStringList arguments;
    arguments << processId;
    arguments << "/Users/zhanghongwei/Desktop/socket-temp/socket-project/res/track";
    process->start(program, arguments);
    socketPath = QDir::temp().absoluteFilePath(processId);
    qDebug() << "System Info:" << QSysInfo::prettyProductName();

    if (!process->waitForStarted()) {
        qDebug() << "Failed to start process.";
    }
    connect(process, &QProcess::readyReadStandardError, this, &Worker::handleProcessOutput);
    connect(process, &QProcess::readyReadStandardOutput, this, &Worker::handleProcessOutput);

    running = true;
}




void Worker::stop() {
    qDebug()<<"进来";
    running = false;
//    disconnect();
    qDebug()<<socket->state();
    if (socket && socket->state() == QLocalSocket::ConnectedState) {
        qDebug()<<"释放socket";
        socket->disconnectFromServer();
        socket->deleteLater();  // 确保 socket 释放
        socket = nullptr;
    }
//    disconnect();
    if (process) {
        qDebug()<<"释放process";
        process->terminate();
        if (!process->waitForFinished(3000)) {
            qDebug()<<"强杀";
            process->kill();
        }
        process->deleteLater();
        process = nullptr;
    }

    if (socket){
        qDebug()<<socket->state();
    }

    if (process){
        qDebug()<<"还在";
    }

    qDebug()<<"完成";
    this->deleteLater();
}
